package cn.yangliu.comm.entity;

import cn.yangliu.comm.BaseException;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.util.Objects;

/**
 * 基础结果json对象
 */

@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = false)
public class JsonResult<T> extends BaseObject {
    private static final long serialVersionUID = 3138145308653310100L;
    public static String SECCESS_CODE = "200";
    public static String SECCESS_MSG = "操作成功";
    protected String code;
    protected String msg;
    protected T data;
    protected static final JsonResult RESULT = new JsonResult();


    public static JsonResult getInstance() {
        RESULT.setCode(SECCESS_CODE);
        RESULT.setMsg(SECCESS_MSG);
        return RESULT;
    }

    public static <E> JsonResult<E> getInstance(E data) {
        JsonResult<E> result = new JsonResult<>(data);
        result.setCode(SECCESS_CODE);
        result.setMsg(SECCESS_MSG);
        return result;
    }

    public JsonResult() {
        this.code = SECCESS_CODE;
        this.msg = SECCESS_MSG;
    }

    public JsonResult(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public JsonResult(String code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public JsonResult(T data) {
        this.code = SECCESS_CODE;
        this.msg = SECCESS_MSG;
        this.data = data;
    }

    public T checkData() {
        if (!Objects.equals(this.code, SECCESS_CODE)) {
            throw new BaseException(code, msg);
        }
        return data;
    }

}
